﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PrintDemo.OtherUtil;

namespace PrintDemo.DBUtil
{
    public class SQLFactory
    {
        private static DBConnSetting _mysqlSetting = null;
        private static IniConfig iniConfig = null;
        /// <summary>
        /// 获取MySQL连接
        /// </summary>
        /// <returns>数据库连接</returns>
        public static MySqlHelper GetMySqlHelper()
        {
            if (_mysqlSetting == null)
            {
                _mysqlSetting = new DBConnSetting();
                _mysqlSetting = GetOPDDbConfig();
            }
            MySqlHelper helperMySql = new MySqlHelper(_mysqlSetting.Server, _mysqlSetting.DbName, _mysqlSetting.User, _mysqlSetting.Psw);
            return helperMySql;
        }
        /// <summary>
        /// 获取数据库设置
        /// </summary>
        /// <returns></returns>
        public static DBConnSetting GetOPDDbConfig()
        {
            DBConnSetting set = new DBConnSetting();
            try
            {
                iniConfig = new IniConfig("DbSetting.ini");
                var flag = iniConfig.KeyExists("Server", "MySQLSetting");
                if (!flag)
                    return null;
                flag = iniConfig.KeyExists("DbName", "MySQLSetting");
                if (!flag)
                    return null;
                flag = iniConfig.KeyExists("User", "MySQLSetting");
                if (!flag)
                    return null;
                flag = iniConfig.KeyExists("Psw", "MySQLSetting");
                if (!flag)
                    return null;
                set.Server = iniConfig.Read("Server", "MySQLSetting");
                set.DbName = iniConfig.Read("DbName", "MySQLSetting");
                string user = iniConfig.Read("User", "MySQLSetting");
                if (user != string.Empty)
                    set.User = Base64Util.Base64Decode(Encoding.UTF8, user);//DataProtector.DecryptLocalMachine(user, DataProtector.SALT);
                string psw = iniConfig.Read("Psw", "MySQLSetting");
                if (psw != string.Empty)
                    set.Psw = Base64Util.Base64Decode(Encoding.UTF8, psw);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return set;
        }
    }
}
